/**
 * 
 */
package com.lanhai.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;

/**
 * @author LM 
 */
public class DBHelper {
	
	/**
	 * 本地连接
	 */
	private DruidPooledConnection connection = null;
	private Statement stmt = null;
	private ResultSet resultSet = null;

	/**
	 * close
	 */
	public void close() {
		try {
			if (connection != null) {
				connection.close();
			}
			if (resultSet != null) {
				resultSet.close();
			}
			if (stmt != null) {
				stmt.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public ResultSet executeQuery(String sql, DruidDataSource dataSource) {
		ResultSet resultSet = null;
		try {
			this.connection = dataSource.getConnection();
			stmt = this.connection.createStatement();
			resultSet = stmt.executeQuery(sql);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultSet;
	}

	/**
	 * 
	 * @param sql
	 * @throws Exception
	 */
	public void executeUpdate(String sql, DruidDataSource dataSource) throws Exception {
		this.connection = dataSource.getConnection();
		stmt = this.connection.createStatement();
		stmt.executeUpdate(sql);
		close();
	}

	/**
	 * 
	 * @param sql
	 * @throws SQLException
	 */
	public void execute(String sql, DruidDataSource dataSource) throws SQLException {
		stmt = null;
		this.connection = dataSource.getConnection();
		stmt = this.connection.createStatement();
		stmt.execute(sql);
		close();
	}

	/**
	 * 记录条数
	 * 
	 * @param sql
	 * @return
	 * @throws SQLException
	 */
	public Long getCount(String sql, DruidDataSource dataSource) throws SQLException {
		Long count = 0L;
		stmt = null;
		resultSet = null;
		this.connection = dataSource.getConnection();
		stmt = this.connection.createStatement();
		resultSet = stmt.executeQuery(sql);
		if (resultSet != null && resultSet.next()) {
			count = new Long(resultSet.getFetchSize());
		}
		close();
		return count;
	}

	public Statement getStmt() {
		return stmt;
	}

	public void setStmt(Statement stmt) {
		this.stmt = stmt;
	}

	public ResultSet getResultSet() {
		return resultSet;
	}

	public void setResultSet(ResultSet resultSet) {
		this.resultSet = resultSet;
	}
}
